<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Session;
class Index extends Controller{
    public function index(){
        if (!Session::has('admin')){
            $this->redirect('login');
        }
        return view();
    }


    public function ismoblie(){
        $this->view->engine->layout(false);
        return view();
    }

    public function login(){
        $this->view->engine->layout(false);
        return view();
    }

    public function mylogin(){
        if (request()->post()) {
            $name = input('post.name');
            $psw = input('post.psw');
            $data = Db::table('admin')->field('psw,salt,apartment')->where('name', $name)->find();
            if (!$data) {
               return 1;
            } else {
                if ($data['psw'] ==$this->password($psw, $data['salt'])) {
                    Session::set('admin', $name);
                    Session::set('apartment', $data['apartment']);
                    return 2;
                }
            }
        }
    }

    public function admin(){
        if (!Session::has('admin')){
            $this->redirect('login');
        }else{
            if (Session::get('apartment')!==''){
                $admin=Db::table('admin')->where('apartment',Session::get('apartment'))->paginate();
                $this->assign('admin',$admin);
            }else{
                $admin=Db::table('admin')->paginate(30);
                $this->assign('admin',$admin);
                $this->assign('all','all');
            }

        }

        return view();
    }
public function deleteadmin(){
    Db::table('admin')->where('id',input('get.id'))->delete();
    $this->redirect($_SERVER["HTTP_REFERER"]);
}

public function changepsw(){
        if (request()->get()){
            $this->assign('id',input('get.id'));
        }
        if (request()->isPost()){
         $id=input('post.id');
         $data['salt'] = substr(uniqid(), -6);
         $data['psw'] = $this->password(input('post.psw'), $data['salt']);
         Db::table('admin')->where('id',$id)->update($data);
            $this->success('修改成功','admin');
        }
        return view();
}

public function add(){
        if (request()->isPost()){
            $data['name']=input('post.name');
            $data['apartment']=input('post.apartment');
            $data['phone']=input('post.phone');
            $data['salt'] = substr(uniqid(), -6);
            $data['psw'] = $this->password(input('post.psw'), $data['salt']);
            Db::table('admin')->insert($data);
            $this->success('添加成功','admin');
        }
        $apartment=Db::table('apartment')->select();
        $this->assign('apartment',$apartment);
        return view();
}
    //退出登陆
    public function logout(){
        Session::clear();
        $this->redirect('login');
    }
    //密码加密函数
    private function password($psw,$salt){
        return md5(md5($psw).$salt);
    }

}
